import falcon

from WebBackend.dataclass.Configuration import get_item_from_ArrayCI
from WebBackend.interface.management.OptionItems.o_user_anony import ANONYMOUS_OPTIONS
from WebBackend.interface.management.OptionItems.o_global import GLOBAL_OPTIONS
from WebBackend.interface.management.OptionItems.o_user_local import LOCAL_USER_OPTIONS
from WebBackend.interface.management.OptionItems.o_user_virtual import VIRTUAL_USER_OPTIONS
from WebBackend.middleware.virtualWorldGate_Chuche import login_require
from WebBackend.store.ConfigurationStore import ConfigurationStore

@falcon.before(login_require)
class OptionItemsAPI:
    def __init__(self, config=None):
        self.config_store: ConfigurationStore = config

    async def on_get(self, req, resp):
        type = req.params.get('type')
        ############################################
        response_data: list[dict] = []
        if type == 'global':
            for item in GLOBAL_OPTIONS:
                response_data.append(self.config_store.configuration_item_wrapper(item))
            response_data.sort(key=lambda x: not x['active'])
        ############################################
        elif type == 'local_user':
            for item in LOCAL_USER_OPTIONS:
                response_data.append(self.config_store.configuration_item_wrapper(item))
            response_data.sort(key=lambda x: not x['active'])
        ############################################
        elif type == 'virtual_user':
            for item in VIRTUAL_USER_OPTIONS:
                response_data.append(self.config_store.configuration_item_wrapper(item))
            response_data.sort(key=lambda x: not x['active'])
        ############################################
        elif type == 'anonymous_user':
            for item in ANONYMOUS_OPTIONS:
                response_data.append(self.config_store.configuration_item_wrapper(item))
            response_data.sort(key=lambda x: not x['active'])
        ############################################
        else:
            raise falcon.HTTPBadRequest(title="未知类型")
        resp.media = response_data

    async def on_post(self, req, resp):
        data: dict = await req.get_media()
        k = data.get('k')
        v = data.get('v')
        bool_key_valid: bool = False
        if k in [item['key'] for item in GLOBAL_OPTIONS]:
            bool_key_valid = True
        if k in [item['key'] for item in LOCAL_USER_OPTIONS]:
            bool_key_valid = True
        if k in [item['key'] for item in VIRTUAL_USER_OPTIONS]:
            bool_key_valid = True
        if k in [item['key'] for item in ANONYMOUS_OPTIONS]:
            bool_key_valid = True
        if bool_key_valid:
            self.config_store.update_data_by_key(k, v)
        else:
            raise falcon.HTTPBadRequest(title='key not found')

    async def on_put(self, req, resp):
        # PUT只用来开关功能，不对值进行修改
        req_key: str | None = req.params.get('k')
        if not req_key:
            raise falcon.HTTPBadRequest(title="请求参数错误：f丢失")
        key_valid = get_item_from_ArrayCI(req_key, GLOBAL_OPTIONS)
        if not key_valid:
            key_valid = get_item_from_ArrayCI(req_key, LOCAL_USER_OPTIONS)
        if not key_valid:
            key_valid = get_item_from_ArrayCI(req_key, VIRTUAL_USER_OPTIONS)
        if not key_valid:
            key_valid = get_item_from_ArrayCI(req_key, ANONYMOUS_OPTIONS)
        if not key_valid:
            raise falcon.HTTPNotFound(title="请求的键不存在")
        else:
            if self.config_store.get_data_by_key(req_key) is not None:
                # 有值就删掉
                self.config_store.update_data_by_key(key_valid['key'], 'del', 'delete')
                resp.media = {'default': key_valid['default']}
            else:
                # 无值就创建
                self.config_store.update_data_by_key(key_valid['key'], key_valid['default'])
                resp.media = {'default': key_valid['default']}
